<template>
	<view class="admin-container">
		<!-- 顶部标题栏 -->
		<view class="admin-header">
			<view class="header-left">
				<text class="admin-title">教师打卡管理</text>
				<text class="admin-subtitle">{{ currentDate }} {{ currentTime }}</text>
			</view>
			<image class="admin-avatar" src="/static/images/admin-avatar.png"></image>
		</view>

		<!-- 统计卡片 -->
		<view class="stats-card">
			<view class="stats-row">
				<view class="stat-item">
					<text class="stat-value">{{ stats.totalTeachers }}</text>
					<text class="stat-label">教师总数</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ stats.checkedIn }}</text>
					<text class="stat-label">已签到</text>
				</view>
			</view>
			<view class="stats-row">
				<view class="stat-item">
					<text class="stat-value">{{ stats.checkedOut }}</text>
					<text class="stat-label">已签退</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ stats.absent }}</text>
					<text class="stat-label">未签到</text>
				</view>
			</view>
		</view>

		<!-- 功能按钮 -->
		<view class="action-buttons">

			<view class="action-btn success" @click="showAllRecords">
				<uni-icons type="list" size="28" color="#fff"></uni-icons>
				<text>全部记录</text>
			</view>
			<view class="action-btn warning" @click="showTeacherSelector">
				<uni-icons type="person" size="28" color="#fff"></uni-icons>
				<text>教师查询</text>
			</view>
			<view class="action-btn primary" @click="generateCheckCode">
				<uni-icons type="right" size="28" color="#fff"></uni-icons>
				<text>发放密码</text>
			</view>
		</view>

		<!-- 最近打卡记录 -->
		<view class="recent-records">
			<view class="section-header">
				<text class="section-title">今日打卡记录</text>
				<!-- <text class="view-all" @click="showAllRecords">查看全部</text> -->
			</view>
			<view class="record-list">
				<view class="record-item" v-for="(record, index) in recentRecords" :key="index"
					@click="viewTeacherDetail(record)">
					<image class="teacher-avatar" :src="record.avatarUrl || '/static/images/default-avatar.png'">
					</image>
					<view class="record-info">
						<text class="teacher-name">{{ record.name }}</text>
						<view class="record-details">
							<text class="record-time">{{ record.checkInTime || '未签到' }}</text>
							<text class="record-status"
								:class="getStatusClass(record)">{{ getStatusText(record) }}</text>
						</view>
					</view>
					<uni-icons type="arrowright" size="20" color="#999"></uni-icons>
				</view>
			</view>
		</view>

		<!-- 教师选择弹出层 -->
		<uni-popup ref="teacherPopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">选择教师</text>
					<uni-icons type="closeempty" size="28" color="#999" @click="closeTeacherPopup"></uni-icons>
				</view>
				<view class="search-bar">
					<uni-icons type="search" size="20" color="#999"></uni-icons>
					<input class="search-input" placeholder="输入教师姓名或工号" v-model="searchKeyword"
						@input="searchTeachers" />
				</view>
				<scroll-view class="teacher-list" scroll-y>
					<view class="teacher-item" v-for="teacher in filteredTeachers" :key="teacher.teacherId"
						@click="viewTeacherRecord(teacher)">
						<image class="teacher-avatar" :src="teacher.avatarUrl || '/static/images/default-avatar.png'">
						</image>
						<view class="teacher-info">
							<text class="teacher-name">{{ teacher.name }}</text>
							<text class="teacher-id">工号: {{ teacher.teacherId }}</text>
						</view>
						<uni-icons type="arrowright" size="20" color="#999"></uni-icons>
					</view>
				</scroll-view>
			</view>
		</uni-popup>

		<!-- 密码生成提示 -->
		<uni-popup ref="codePopup" type="message">
			<uni-popup-message type="success" :message="codeMessage" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				currentTime: this.formatTime(new Date()),
				currentDate: this.formatDate(new Date()),
				stats: {
					totalTeachers: 0,
					checkedIn: 0,
					checkedOut: 0,
					absent: 0
				},
				allTeachers: [],
				filteredTeachers: [],
				recentRecords: [],
				searchKeyword: '',
				timeInterval: null,
				codeMessage: ''
			};
		},
		onLoad() {
			this.startTimeUpdater();
			this.fetchAllTeachers();
			// this.fetchStats();
		},
		onUnload() {
			this.stopTimeUpdater();
		},
		methods: {
			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			startTimeUpdater() {
				this.stopTimeUpdater();
				this.timeInterval = setInterval(() => {
					this.currentTime = this.formatTime(new Date());
				}, 60000);
			},
			stopTimeUpdater() {
				if (this.timeInterval) {
					clearInterval(this.timeInterval);
					this.timeInterval = null;
				}
			},
			async fetchAllTeachers() {
				try {
					const res = await uni.request({
						url: `${globalVariable}/getAllTeachers`,
						method: 'GET'
					});

					if (res.data && res.data.status === 1) {
						this.allTeachers = res.data.data;
						this.filteredTeachers = [...this.allTeachers];
						this.stats.totalTeachers = this.allTeachers.length;
						this.fetchRecentRecords();
					}
				} catch (error) {
					console.error('获取教师列表失败:', error);
					uni.showToast({
						title: '获取教师列表失败',
						icon: 'none'
					});
				}
			},
			async fetchTeacherCheck(teacherId) {
				try {
					const res = await uni.request({
						url: `${globalVariable}/getTeacherCheck?teacherId=${teacherId}&date=${this.currentDate}`,
						method: 'GET'
					});

					if (res.data) {
						if (res.data.status === 1) {
							return res.data.data;
						} else if (res.data.status === 2) {
							return {
								checkInTime: null,
								checkOutTime: null
							};
						}
					}
					return null;
				} catch (error) {
					console.error('获取教师打卡记录失败:', error);
					return null;
				}
			},
			async fetchRecentRecords() {
				try {
					// 获取最近5位教师的打卡记录
					const recentTeachers = this.allTeachers;
					const records = [];

					for (const teacher of recentTeachers) {
						const checkRecord = await this.fetchTeacherCheck(teacher.teacherId);
						records.push({
							...teacher,
							checkInTime: checkRecord?.checkInTime || null,
							checkOutTime: checkRecord?.checkOutTime || null
						});
					}

					this.recentRecords = records;
					this.updateStats();
				} catch (error) {
					console.error('获取最近记录失败:', error);
				}
			},
			updateStats() {
				let checkedIn = 0;
				let checkedOut = 0;

				this.recentRecords.forEach(record => {
					if (record.checkInTime) checkedIn++;
					if (record.checkOutTime) checkedOut++;
				});

				this.stats.checkedIn = checkedIn;
				this.stats.checkedOut = checkedOut;
				this.stats.absent = this.recentRecords.length - checkedIn;
			},
			getStatusClass(record) {
				if (record.checkInTime) {
					return record.checkOutTime ? 'success' : 'warning';
				}
				return 'error';
			},
			getStatusText(record) {
				if (record.checkInTime) {
					return record.checkOutTime ? '已完成' : '已签到';
				}
				return '未签到';
			},
			refreshStats() {
				this.fetchRecentRecords();
				uni.showToast({
					title: '数据已刷新',
					icon: 'none'
				});
			},
			generateCheckCode() {
				// uni.showLoading({
				// 	title: '生成中...'
				// });
				// setTimeout(() => {
				// 	uni.hideLoading();
				// 	this.codeMessage = '已生成今日签到码: 5689';
				// 	this.$refs.codePopup.open();
				// }, 1000);
				uni.navigateTo({
					url:"/pages/checkpassword/checkpassword"
				})
			},
			showAllRecords() {
				uni.navigateTo({
					url: '/pages/admin/allRecords'
				});
			},
			showTeacherSelector() {
				this.$refs.teacherPopup.open();
			},
			closeTeacherPopup() {
				this.$refs.teacherPopup.close();
				this.searchKeyword = '';
				this.filteredTeachers = [...this.allTeachers];
			},
			searchTeachers() {
				if (!this.searchKeyword) {
					this.filteredTeachers = [...this.allTeachers];
					return;
				}
				const keyword = this.searchKeyword.toLowerCase();
				this.filteredTeachers = this.allTeachers.filter(teacher =>
					teacher.name.toLowerCase().includes(keyword) ||
					teacher.teacherId.toString().includes(keyword)
				);
			},
			async viewTeacherRecord(teacher) {
				this.$refs.teacherPopup.close();

				// 获取该教师的打卡记录
				const checkRecord = await this.fetchTeacherCheck(teacher.teacherId);

				uni.navigateTo({
					url: `/pages/admin/teacherRecord?id=${teacher.teacherId}&name=${encodeURIComponent(teacher.name)}`,
					success: (res) => {
						res.eventChannel.emit('sendCheckRecord', {
							teacher: teacher,
							checkRecord: checkRecord
						});
					}
				});
			},
			viewTeacherDetail(record) {
				uni.navigateTo({
					url: `/pages/admin/teacherRecord?id=${record.teacherId}&name=${encodeURIComponent(record.name)}`,
					success: (res) => {
						res.eventChannel.emit('sendCheckRecord', {
							teacher: record,
							checkRecord: {
								checkInTime: record.checkInTime,
								checkOutTime: record.checkOutTime
							}
						});
					}
				});
			}
		}
	};
</script>

<style lang="scss">
	/* 颜色定义 */
	$primary-color: #4D59FF;
	$success-color: #4CAF50;
	$warning-color: #FFC107;
	$error-color: #F44336;
	$text-color: #333;
	$text-light: #666;
	$text-lighter: #999;
	$border-color: #eee;
	$bg-color: #f5f7fa;
	$card-bg: #fff;
	$shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

	.admin-container {
		padding: 20rpx;
		background-color: $bg-color;
		min-height: 100vh;
	}

	/* 顶部标题 */
	.admin-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		background-color: $card-bg;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		box-shadow: $shadow;

		.header-left {
			display: flex;
			flex-direction: column;
		}

		.admin-title {
			font-size: 36rpx;
			font-weight: bold;
			color: $text-color;
			margin-bottom: 8rpx;
		}

		.admin-subtitle {
			font-size: 24rpx;
			color: $text-light;
		}

		.admin-avatar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			border: 2rpx solid #f0f0f0;
		}
	}

	/* 统计卡片 */
	.stats-card {
		background-color: $card-bg;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: $shadow;

		.stats-row {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;

			&:last-child {
				margin-bottom: 0;
			}
		}

		.stat-item {
			flex: 1;
			text-align: center;
			padding: 20rpx;
			background-color: #f8f9fa;
			border-radius: 12rpx;
			margin: 0 10rpx;

			.stat-value {
				font-size: 40rpx;
				font-weight: bold;
				color: $primary-color;
				display: block;
				margin-bottom: 10rpx;
			}

			.stat-label {
				font-size: 26rpx;
				color: $text-light;
				display: block;
			}
		}
	}

	/* 功能按钮 */
	.action-buttons {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;

		.action-btn {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 25rpx 0;
			border-radius: 12rpx;
			color: #fff;
			font-size: 28rpx;
			margin: 0 10rpx;

			&.primary {
				background-color: $primary-color;
			}

			&.success {
				background-color: $success-color;
			}

			&.warning {
				background-color: $warning-color;
			}

			uni-icons {
				margin-bottom: 10rpx;
			}
		}
	}

	/* 最近打卡记录 */
	.recent-records {
		background-color: $card-bg;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: $shadow;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: $text-color;
			}

			.view-all {
				font-size: 26rpx;
				color: $primary-color;
			}
		}

		.record-list {
			.record-item {
				display: flex;
				align-items: center;
				padding: 25rpx 0;
				border-bottom: 1rpx solid $border-color;

				&:last-child {
					border-bottom: none;
				}

				.teacher-avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					margin-right: 20rpx;
				}

				.record-info {
					flex: 1;

					.teacher-name {
						font-size: 30rpx;
						color: $text-color;
						display: block;
						margin-bottom: 8rpx;
					}

					.record-details {
						display: flex;
						align-items: center;

						.record-time {
							font-size: 24rpx;
							color: $text-light;
							margin-right: 15rpx;
						}

						.record-status {
							font-size: 24rpx;
							padding: 4rpx 12rpx;
							border-radius: 20rpx;
							background-color: #f0f0f0;

							&.success {
								color: $success-color;
								background-color: rgba(76, 175, 80, 0.1);
							}

							&.warning {
								color: $warning-color;
								background-color: rgba(255, 152, 0, 0.1);
							}

							&.error {
								color: $error-color;
								background-color: rgba(244, 67, 54, 0.1);
							}
						}
					}
				}
			}
		}
	}

	/* 教师选择弹出层 */
	.popup-content {
		background-color: $card-bg;
		border-radius: 30rpx 30rpx 0 0;
		padding: 30rpx;
		max-height: 70vh;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;

			.popup-title {
				font-size: 36rpx;
				font-weight: bold;
				color: $text-color;
			}
		}

		.search-bar {
			display: flex;
			align-items: center;
			background-color: #f5f7fa;
			border-radius: 50rpx;
			padding: 20rpx 30rpx;
			margin-bottom: 30rpx;

			.search-input {
				flex: 1;
				font-size: 28rpx;
				margin-left: 15rpx;
				color: $text-color;
			}
		}

		.teacher-list {
			max-height: 50vh;

			.teacher-item {
				display: flex;
				align-items: center;
				padding: 25rpx 0;
				border-bottom: 1rpx solid $border-color;

				&:last-child {
					border-bottom: none;
				}

				.teacher-avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					margin-right: 20rpx;
				}

				.teacher-info {
					flex: 1;

					.teacher-name {
						font-size: 30rpx;
						color: $text-color;
						display: block;
						margin-bottom: 5rpx;
					}

					.teacher-id {
						font-size: 24rpx;
						color: $text-light;
						display: block;
					}
				}
			}
		}
	}
</style>